﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using Cricket.LinqModel;
using Cricket.LinqData;
using System.Web.Script.Services;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;

public partial class ClientBetting : System.Web.UI.Page
{
    IDataRepository _dataObject = new DataRepository();
    MatchSchedule matchSchedule;
    BettingType bettingType;
    List<BettingType> bettingTypes;
    MatchType matchType;
    List<MatchType> matchTypes;
    CustomerBetting customerBetting;
    List<CustomerBetting> customerBettings = new List<CustomerBetting>();
    CommissionAmount commissionAmount;
    Client client;
    

    int Team1 = 0;
    int Team2 = 0;
    decimal? matchAmount = 0;
    decimal? sessionAmount = 0;
    decimal? total = 0;    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            
            HttpCookie cookie = Request.Cookies["Client"];
            if (cookie == null)
            {
                Response.Redirect("Login.aspx");
            }
            else
            {
                
                
                bindMatchType();
                hdnAdminId.Value = Convert.ToString(cookie["AdminId"]);
                hdnClientId.Value = Convert.ToString(cookie["ClientId"]);
                if (Request.QueryString["Id"] != null)
                    getDropdownsSelected(Convert.ToInt32(Request.QueryString["Id"].ToString()));
            }
        }
    }

    private void getDropdownsSelected(int matchScheduleId)
    {
        DataTable dt = GetData("select * from MatchSchedule where Id = " + matchScheduleId.ToString());
        drpMatchType.SelectedValue = dt.Rows[0]["MatchType"].ToString();
        bindMatch();
        drpMatch.SelectedValue = matchScheduleId.ToString();
        drpMatch_SelectedIndexChanged(null, null);
        drpMatchType.Enabled = false;
        drpMatch.Enabled = false;
    }
    //private void bindBettingLimit()
    //{
    //    Client client = new Client(_dataObject);
    //    client = new Client(_dataObject);
    //    if (drpBettingType.SelectedItem.Text.ToLower().Equals("match"))
    //        spBettingLimit.Text = client.GetMatchClientBettingLimit(Convert.ToInt32(hdnClientId.Value)).ToString();
    //    else
    //        spBettingLimit.Text = client.GetClientBettingLimit(Convert.ToInt32(hdnClientId.Value)).ToString();

    //}
    private void bindBettingLimit()
    {
        HttpCookie cookie = Request.Cookies["Client"];
        Client client = new Client(_dataObject);
        client = new Client(_dataObject);


        List<GetMinAmountForMatchResult> lst = new List<GetMinAmountForMatchResult>();
        lst = client.GetMinAmountForMatch(Convert.ToInt32(drpMatch.SelectedValue), Convert.ToInt32(cookie["ClientId"]));
        if (lst.Count > 0)
        {
            matchAmount = (lst[0].MinAmount);
            if (matchAmount == null)
            {
                matchAmount = 0;
            }
            //if (matchAmount > 0)
            //{
            //    matchLimit = Convert.ToDecimal(cookie["ActualLimit"]) + matchAmount;
            //}
            //else if (matchAmount == 0)
            //{
            //    matchLimit = 0;
            //}
            //else
            //{
            //    matchLimit = Convert.ToDecimal(cookie["ActualLimit"]) + matchAmount;
            //}

        }
        List<GetTotalAmountForSessionResult> lst1 = new List<GetTotalAmountForSessionResult>();
        lst1 = client.GetTotalAmountForSession(Convert.ToInt32(drpMatch.SelectedValue), Convert.ToInt32(cookie["ClientId"]));
        if (lst1.Count > 0)
        {
            sessionAmount = lst1[0].SessionAmount;
            if (sessionAmount == null)
            {
                sessionAmount = 0;
            }
            //else
            //{
            //    sessionLimit = Convert.ToDecimal(cookie["ActualLimit"]) - sessionAmount;
            //}
        }

        total = matchAmount + sessionAmount;
        if (total != null)
        {
            //if (matchAmount != 0 || sessionAmount != 0)
            //{
            //    spBettingLimit.Text = Convert.ToString(matchLimit + sessionLimit);
            //}
            //else
            //{
            //    spBettingLimit.Text = Convert.ToString(cookie["ActualLimit"]);
            //}
            //if (matchAmount >= 0)
            //{
            //    spBettingLimit.Text = Convert.ToString(Convert.ToDecimal(cookie["ActualLimit"]) + matchAmount - sessionAmount);
            //}
            //else
            //{
            //    spBettingLimit.Text = Convert.ToString(Convert.ToDecimal(cookie["ActualLimit"]) - matchAmount - sessionAmount);
            //}
            client = new Client(_dataObject);
            client.Id = Convert.ToInt32(cookie["ClientId"]);
            client.GetClientById();

            if (client.Id != 0)
                spBettingLimit.Text = Convert.ToString(Convert.ToDecimal(client.ActualLimit) + matchAmount - sessionAmount);
        }
    }
    private void bindMatch()
    {
        matchSchedule = new MatchSchedule(_dataObject);
        List<GetTodayMatcheResult> lstResult = new List<GetTodayMatcheResult>();
        lstResult = matchSchedule.GetTodayMatches(Convert.ToInt32(drpMatchType.SelectedValue));
        if (lstResult != null && lstResult.Count > 0)
        {
            drpMatch.DataSource = lstResult;
            drpMatch.DataTextField = "Teams";
            drpMatch.DataValueField = "Id";
            drpMatch.DataBind();
            drpMatch.Items.Insert(0, new ListItem("Select Match", "0"));
        }
        else
        {
            drpMatch.DataSource = null;
            drpMatch.DataBind();
            drpMatch.Items.Insert(0, new ListItem("Select Match", "0"));
        }
    }
    private void bindBettingType()
    {
        bettingType = new BettingType(_dataObject);
        bettingTypes = new List<BettingType>();
        bettingTypes = bettingType.GetAllBettingType();
        if (bettingTypes.Count > 0)
        {
            drpBettingType.DataSource = bettingTypes;
            drpBettingType.DataTextField = "Type";
            drpBettingType.DataValueField = "Id";
            drpBettingType.DataBind();
            drpBettingType.Items.Insert(0, new ListItem("Select Betting Type", "0"));
        }
    }
    private void bindMatchType()
    {
        matchType = new MatchType(_dataObject);
        matchTypes = new List<MatchType>();
        matchTypes = matchType.GetAllMatchType();
        if (matchTypes.Count > 0)
        {
            drpMatchType.DataSource = matchTypes;
            drpMatchType.DataTextField = "Type";
            drpMatchType.DataValueField = "Id";
            drpMatchType.DataBind();
            drpMatchType.Items.Insert(0, new ListItem("Select Match Type", "0"));
        }
        else
        {
            drpMatchType.DataSource = null;
            drpMatchType.DataBind();
            drpMatchType.Items.Insert(0, new ListItem("Select Match Type", "0"));
        }
    }
    protected void drpMatchType_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (drpMatchType.SelectedValue != "")
            bindMatch();
    }
    protected void drpMatch_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (drpMatch.SelectedItem.Text.ToLower() != "select match" && drpMatch.SelectedItem.Text.ToLower() != "select match type")
        {
            //matchSchedule = new MatchSchedule(_dataObject);
            //List<GetTodayMatcheResult> lstResult = new List<GetTodayMatcheResult>();
            //lstResult = matchSchedule.GetTodayMatches(Convert.ToInt32(drpMatchType.SelectedValue));

            matchSchedule = new MatchSchedule(_dataObject);
            List<GetMatchDetailsResult> lstResult = new List<GetMatchDetailsResult>();
            lstResult = matchSchedule.GetMatchDetails(Convert.ToInt32(drpMatch.SelectedValue));
            lblTeamA.Text = lstResult[0].Team1;
            lblTeamB.Text = lstResult[0].Team2;
            hdnTeamAId.Value = Convert.ToString(lstResult[0].TeamAId);
            hdnTeamBId.Value = Convert.ToString(lstResult[0].TeamBId);
            Team1 = Convert.ToInt32(lstResult[0].TeamAId);
            Team2 = Convert.ToInt32(lstResult[0].TeamBId);
            bindBettingType();
            layerSuccess.Attributes.Add("style", "display:none;");
            BindCustomersMatchReport();
            BindCustomersSessionReport();
        }
    }
    protected void drpBettingType_SelectedIndexChanged(object sender, EventArgs e)
    {
        HttpCookie cookie = Request.Cookies["Client"];
        layerSuccess.Attributes.Add("style", "display:none;");
        layerError.Attributes.Add("style", "display:none;");
        if (drpBettingType.SelectedValue != "")
        {
            switch (drpBettingType.SelectedValue)
            {
                case "1": //Session
                    divOverTeamA.Attributes.Add("style", "display:inline-block;");
                    divOverTeamB.Attributes.Add("style", "display:inline-block;");
                    divOverTie.Attributes.Add("style", "display:none;");
                    divOverDraw.Attributes.Add("style", "display:none;");

                    divOver.Attributes.Add("class", "input-prepend");
                    divLagadi.Attributes.Add("class", "input-prepend");
                    divKhadhi.Attributes.Add("class", "input-prepend");

                    spLagadi.InnerText = "Khadhi";
                    spKhadhi.InnerText = "Lagadi";

                    UpdateClientLimitFromMatch(Convert.ToInt32(cookie["ClientId"]));

                    break;
                case "2": //Match
                    divOverTeamA.Attributes.Add("style", "display:none;");
                    divOverTeamB.Attributes.Add("style", "display:none;");
                    divOverTie.Attributes.Add("style", "display:none;");
                    divOverDraw.Attributes.Add("style", "display:none;");

                    divOver.Attributes.Add("class", "input-prepend hide");
                    divLagadi.Attributes.Add("class", "input-prepend");
                    divKhadhi.Attributes.Add("class", "input-prepend");

                    spLagadi.InnerText = "Lagadi";
                    spKhadhi.InnerText = "Khadhi";

                    UpdateClientLimitFromSession(Convert.ToInt32(cookie["ClientId"]));

                    break;
            }

            divBettingTeamA.Attributes.Add("style", "display:inline-block;");
            divBettingTeamB.Attributes.Add("style", "display:inline-block;");
            if (drpMatchType.SelectedItem.Text.ToLower() == "one day" || drpMatchType.SelectedItem.Text.ToLower() == "t20")
            {
                if (drpBettingType.SelectedItem.Text.ToLower() == "session")
                {
                    divBettingTie.Attributes.Add("style", "display:none;");
                    divBettingDraw.Attributes.Add("style", "display:none;");
                }
                else if (drpBettingType.SelectedItem.Text.ToLower() == "match")
                {
                    divBettingTie.Attributes.Add("style", "display:inline-block;");
                    divBettingDraw.Attributes.Add("style", "display:none;");
                }
            }
            else if (drpMatchType.SelectedItem.Text.ToLower() == "test")
            {
                if (drpBettingType.SelectedItem.Text.ToLower() == "session")
                {
                    divBettingTie.Attributes.Add("style", "display:none;");
                    divBettingDraw.Attributes.Add("style", "display:none;");
                }
                else if (drpBettingType.SelectedItem.Text.ToLower() == "match")
                {
                    divBettingTie.Attributes.Add("style", "display:none;");
                    divBettingDraw.Attributes.Add("style", "display:inline-block;");
                }
            }
            bindBettingLimit();
        }
    }

    private void UpdateClientLimitFromSession(int ClientId)
    {
        client = new Client(_dataObject);
        client.UpdateClientLimitForSession(ClientId);
    }

    private void UpdateClientLimitFromMatch(int ClientId)
    {
        client = new Client(_dataObject);
        client.UpdateClientLimitFromMatch(ClientId);
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        System.Threading.Thread.Sleep(4000);
        btnSubmit.Visible = false;      
        
        HttpCookie cookie = Request.Cookies["Client"];
        if (cookie == null)
        {
            Response.Redirect("Login.aspx");
        }
        else
        {
            matchSchedule = new MatchSchedule(_dataObject);
            List<GetMatchDetailsResult> lstResult = new List<GetMatchDetailsResult>();
            lstResult = matchSchedule.GetMatchDetails(Convert.ToInt32(drpMatch.SelectedValue));
            Team1 = Convert.ToInt32(lstResult[0].TeamAId);
            Team2 = Convert.ToInt32(lstResult[0].TeamBId);
            string amount = "";
            //Team A
            customerBetting = new CustomerBetting(_dataObject);
            customerBetting.MatchSchduleId = Convert.ToInt32(drpMatch.SelectedValue);
            customerBetting.BettingId = TeamABettingId.Text == "" ? 0 : Convert.ToInt32(TeamABettingId.Text);
            customerBetting.Rate = txtSessionLagadiTeamA.Text.Trim().Equals("") ? txtSessionKhadhiTeamA.Text : txtSessionLagadiTeamA.Text;

            customerBetting.BetFor = txtSessionLagadiTeamA.Text.Trim().Equals("") ? "K" : "L";
            if (drpBettingType.SelectedItem.Text.ToLower() == "session")
            {
                if (customerBetting.BetFor == "K")
                {
                    customerBetting.BetFor = "L";
                }
                else if (customerBetting.BetFor == "L")
                {
                    customerBetting.BetFor = "K";
                }
            }
            customerBetting.CreatedBy = Convert.ToInt32(cookie["ClientId"]);
            customerBetting.CreatedDate = System.DateTime.Now;
            customerBetting.TeamAId = Team1;
            customerBetting.IPAdded = "";//crickGen.IPAddress(System.Web.HttpContext.Current);
            if (drpBettingType.SelectedItem.Text.ToLower().Equals("match") && customerBetting.BetFor != "" && customerBetting.Rate != "")
            {
                if (customerBetting.BetFor == "K")
                {
                    customerBetting.TeamAAmount = (Convert.ToDecimal(customerBetting.Rate) * Convert.ToDecimal(hdnTeamAK.Value)) * -1;
                    customerBetting.TeamBAmount = Convert.ToDecimal(customerBetting.Rate);
                    if (drpMatchType.SelectedItem.Text.ToLower() == "one day" || drpMatchType.SelectedItem.Text.ToLower() == "t20")
                    {
                        customerBetting.TieAmount = 0;
                    }
                    else if (drpMatchType.SelectedItem.Text.ToLower() == "test")
                    {
                        customerBetting.DrawAmount = Convert.ToDecimal(customerBetting.Rate);
                    }
                }
                else
                {
                    customerBetting.TeamAAmount = (Convert.ToDecimal(customerBetting.Rate) * Convert.ToDecimal(hdnTeamAL.Value));
                    customerBetting.TeamBAmount = Convert.ToDecimal(customerBetting.Rate) * -1;
                    if (drpMatchType.SelectedItem.Text.ToLower() == "one day" || drpMatchType.SelectedItem.Text.ToLower() == "t20")
                    {
                        customerBetting.TieAmount = 0;
                    }
                    else if (drpMatchType.SelectedItem.Text.ToLower() == "test")
                    {
                        customerBetting.DrawAmount = Convert.ToDecimal(customerBetting.Rate) * -1;
                    }
                }
            }

            if (!string.IsNullOrEmpty(customerBetting.Rate))
            {
                if (Convert.ToDecimal(spBettingLimit.Text) < Convert.ToDecimal(customerBetting.Rate))
                {
                    layerError.Attributes.Add("style", "display:block;");
                    layerError.InnerHtml = "Cannot play above your Limit.";
                    btnSubmit.Visible = true;
                    return;
                }
                else
                {
                    customerBettings.Add(customerBetting);

                    client = new Client(_dataObject);
                    if (drpBettingType.SelectedItem.Text.ToLower().Equals("match"))
                        client.UpdateClientMatchLimit(Convert.ToInt32(drpMatch.SelectedValue), Convert.ToInt32(cookie["ClientId"]));
                    else
                        client.UpdateClientLimit(Convert.ToInt32(cookie["ClientId"]), customerBetting.Rate);
                }
            }

            //Team B
            customerBetting = new CustomerBetting(_dataObject);
            customerBetting.MatchSchduleId = Convert.ToInt32(drpMatch.SelectedValue);
            customerBetting.BettingId = TeamBBettingId.Text == "" ? 0 : Convert.ToInt32(TeamBBettingId.Text);
            customerBetting.Rate = txtSessionLagadiTeamB.Text.Trim().Equals("") ? txtSessionKhadhiTeamB.Text : txtSessionLagadiTeamB.Text;
            customerBetting.BetFor = txtSessionLagadiTeamB.Text.Trim().Equals("") ? "K" : "L";
            if (drpBettingType.SelectedItem.Text.ToLower() == "session")
            {
                if (customerBetting.BetFor == "K")
                {
                    customerBetting.BetFor = "L";
                }
                else if (customerBetting.BetFor == "L")
                {
                    customerBetting.BetFor = "K";
                }
            }
            customerBetting.CreatedBy = Convert.ToInt32(cookie["ClientId"]);
            customerBetting.CreatedDate = System.DateTime.Now;
            customerBetting.TeamBId = Team2;
            customerBetting.IPAdded = "";//crickGen.IPAddress(System.Web.HttpContext.Current);
            if (drpBettingType.SelectedItem.Text.ToLower().Equals("match") && customerBetting.BetFor != "" && customerBetting.Rate != "")
            {
                if (customerBetting.BetFor == "K")
                {
                    customerBetting.TeamAAmount = Convert.ToDecimal(customerBetting.Rate);
                    customerBetting.TeamBAmount = (Convert.ToDecimal(customerBetting.Rate) * Convert.ToDecimal(hdnTeamBK.Value)) * -1;
                    if (drpMatchType.SelectedItem.Text.ToLower() == "one day" || drpMatchType.SelectedItem.Text.ToLower() == "t20")
                    {
                        customerBetting.TieAmount = 0;
                    }
                    else if (drpMatchType.SelectedItem.Text.ToLower() == "test")
                    {
                        customerBetting.DrawAmount = Convert.ToDecimal(customerBetting.Rate);
                    }
                }
                else
                {
                    customerBetting.TeamAAmount = Convert.ToDecimal(customerBetting.Rate) * -1;
                    customerBetting.TeamBAmount = (Convert.ToDecimal(customerBetting.Rate) * Convert.ToDecimal(hdnTeamBL.Value));
                    if (drpMatchType.SelectedItem.Text.ToLower() == "one day" || drpMatchType.SelectedItem.Text.ToLower() == "t20")
                    {
                        customerBetting.TieAmount = 0;
                    }
                    else if (drpMatchType.SelectedItem.Text.ToLower() == "test")
                    {
                        customerBetting.DrawAmount = Convert.ToDecimal(customerBetting.Rate) * -1;
                    }
                }
            }

            if (!string.IsNullOrEmpty(customerBetting.Rate))
            {
                if (Convert.ToDecimal(spBettingLimit.Text) < Convert.ToDecimal(customerBetting.Rate))
                {
                    layerError.Attributes.Add("style", "display:block;");
                    layerError.InnerHtml = "Cannot play above your Limit.";
                    btnSubmit.Visible= true;
                    return;
                }
                else
                {
                    customerBettings.Add(customerBetting);

                    client = new Client(_dataObject);
                    if (drpBettingType.SelectedItem.Text.ToLower().Equals("match"))
                        client.UpdateClientMatchLimit(Convert.ToInt32(drpMatch.SelectedValue), Convert.ToInt32(cookie["ClientId"]));
                    else
                        client.UpdateClientLimit(Convert.ToInt32(cookie["ClientId"]), customerBetting.Rate);
                }
            }

            //Team Tie
            customerBetting = new CustomerBetting(_dataObject);
            customerBetting.MatchSchduleId = Convert.ToInt32(drpMatch.SelectedValue);
            customerBetting.BettingId = TeamTieBettingId.Text == "" ? 0 : Convert.ToInt32(TeamTieBettingId.Text);
            customerBetting.Rate = txtSessionLagadiTeamTie.Text.Trim().Equals("") ? txtSessionKhadhiTeamTie.Text : txtSessionLagadiTeamTie.Text;
            customerBetting.BetFor = txtSessionLagadiTeamTie.Text.Trim().Equals("") ? "K" : "L";
            if (drpBettingType.SelectedItem.Text.ToLower() == "session")
            {
                if (customerBetting.BetFor == "K")
                {
                    customerBetting.BetFor = "L";
                }
                else if (customerBetting.BetFor == "L")
                {
                    customerBetting.BetFor = "K";
                }
            }
            customerBetting.CreatedBy = Convert.ToInt32(cookie["ClientId"]);
            customerBetting.CreatedDate = System.DateTime.Now;
            customerBetting.IPAdded = "";//crickGen.IPAddress(System.Web.HttpContext.Current);
            if (drpBettingType.SelectedItem.Text.ToLower().Equals("match") && customerBetting.BetFor != "" && customerBetting.Rate != "")
            {
                if (customerBetting.BetFor == "K")
                {
                    customerBetting.TeamAAmount = 0;
                    customerBetting.TeamBAmount = 0;
                    customerBetting.TieAmount = (Convert.ToDecimal(customerBetting.Rate) * Convert.ToDecimal(hdnTieK.Value)) * -1;
                }
                else
                {
                    customerBetting.TeamAAmount = 0;
                    customerBetting.TeamBAmount = 0;
                    customerBetting.TieAmount = (Convert.ToDecimal(customerBetting.Rate) * Convert.ToDecimal(hdnTieL.Value));
                }
            }
            //customerBetting.BettingAmount = Convert.ToDecimal(customerBetting.BetFor == "K" ? Convert.ToDouble(spSessionKhadhiTeamTie.InnerHtml) : Convert.ToDouble(spSessionLagadiTeamTie.InnerHtml) * Convert.ToDouble(customerBetting.Rate));

            if (!string.IsNullOrEmpty(customerBetting.Rate))
            {
                if (Convert.ToDecimal(spBettingLimit.Text) < Convert.ToDecimal(customerBetting.Rate))
                {
                    layerError.Attributes.Add("style", "display:block;");
                    layerError.InnerHtml = "Cannot play above your Limit.";
                    btnSubmit.Visible = true;
                    return;
                }
                else
                {
                    customerBettings.Add(customerBetting);

                    client = new Client(_dataObject);
                    if (drpBettingType.SelectedItem.Text.ToLower().Equals("match"))
                        client.UpdateClientMatchLimit(Convert.ToInt32(drpMatch.SelectedValue), Convert.ToInt32(cookie["ClientId"]));
                    else
                        client.UpdateClientLimit(Convert.ToInt32(cookie["ClientId"]), customerBetting.Rate);
                }
            }

            //Team Draw
            customerBetting = new CustomerBetting(_dataObject);
            customerBetting.MatchSchduleId = Convert.ToInt32(drpMatch.SelectedValue);
            customerBetting.BettingId = TeamDrawBettingId.Text == "" ? 0 : Convert.ToInt32(TeamDrawBettingId.Text);
            customerBetting.Rate = txtSessionLagadiTeamDraw.Text.Trim().Equals("") ? txtSessionKhadhiTeamDraw.Text : txtSessionLagadiTeamDraw.Text;
            customerBetting.BetFor = txtSessionLagadiTeamDraw.Text.Trim().Equals("") ? "K" : "L";
            if (drpBettingType.SelectedItem.Text.ToLower() == "session")
            {
                if (customerBetting.BetFor == "K")
                {
                    customerBetting.BetFor = "L";
                }
                else if (customerBetting.BetFor == "L")
                {
                    customerBetting.BetFor = "K";
                }
            }
            customerBetting.CreatedBy = Convert.ToInt32(cookie["ClientId"]);
            customerBetting.CreatedDate = System.DateTime.Now;
            customerBetting.IPAdded = "";//crickGen.IPAddress(System.Web.HttpContext.Current);
            if (drpBettingType.SelectedItem.Text.ToLower().Equals("match") && customerBetting.BetFor != "" && customerBetting.Rate != "")
            {
                if (customerBetting.BetFor == "K")
                {
                    customerBetting.TeamAAmount = Convert.ToDecimal(customerBetting.Rate);
                    customerBetting.TeamBAmount = Convert.ToDecimal(customerBetting.Rate);
                    customerBetting.DrawAmount = (Convert.ToDecimal(customerBetting.Rate) * Convert.ToDecimal(hdnDrawK.Value)) * -1;

                }
                else
                {
                    customerBetting.TeamAAmount = Convert.ToDecimal(customerBetting.Rate) * -1;
                    customerBetting.TeamBAmount = Convert.ToDecimal(customerBetting.Rate) * -1;
                    customerBetting.DrawAmount = (Convert.ToDecimal(customerBetting.Rate) * Convert.ToDecimal(hdnDrawL.Value));
                }
            }

            //if (Convert.ToDecimal(spBettingLimit.InnerHtml) < Convert.ToDecimal(customerBettings[0].Rate))
            //{
            //    layerError.Attributes.Add("style", "display:block;");
            //    layerError.InnerHtml = "Limit is over!";
            //    return;
            //}
            //else
            //{
            if (!string.IsNullOrEmpty(customerBetting.Rate))
            {
                if (Convert.ToDecimal(spBettingLimit.Text) < Convert.ToDecimal(customerBetting.Rate))
                {
                    layerError.Attributes.Add("style", "display:block;");
                    layerError.InnerHtml = "Cannot play above your Limit.";
                    btnSubmit.Visible = true;
                    return;
                }
                else
                {
                    customerBettings.Add(customerBetting);

                    client = new Client(_dataObject);
                    if (drpBettingType.SelectedItem.Text.ToLower().Equals("match"))
                        client.UpdateClientMatchLimit(Convert.ToInt32(drpMatch.SelectedValue), Convert.ToInt32(cookie["ClientId"]));
                    else
                        client.UpdateClientLimit(Convert.ToInt32(cookie["ClientId"]), customerBetting.Rate);
                }
            }

            customerBetting.CreateCustomerBetting(customerBettings);

            client = new Client(_dataObject);
            if (drpBettingType.SelectedItem.Text.ToLower().Equals("match"))
                client.UpdateClientMatchLimit(Convert.ToInt32(drpMatch.SelectedValue), Convert.ToInt32(cookie["ClientId"]));
            else
            {
                if (customerBetting.Rate != "")
                {
                    client.UpdateClientLimit(Convert.ToInt32(cookie["ClientId"]), customerBetting.Rate);
                }
            }
            if (drpBettingType.SelectedItem.Text.ToLower().Trim() == "session")
            {
                for (int i = 0; i < customerBettings.Count; i++)
                {
                    commissionAmount = new CommissionAmount(_dataObject);
                    commissionAmount.ClientId = Convert.ToInt32(cookie["ClientId"]);
                    commissionAmount.BettingId = customerBettings[i].BettingId;
                    commissionAmount.CommissionAmount1 = Convert.ToString(Convert.ToDecimal(customerBettings[i].Rate) * Convert.ToDecimal(cookie["Commission"]) / 100);
                    commissionAmount.CreatedDate = System.DateTime.Now;
                    commissionAmount.AdminId = Convert.ToInt32(cookie["AdminId"]);
                    commissionAmount.MatchId = Convert.ToInt32(drpMatch.SelectedValue);
                    commissionAmount.Create();
                }
            }

            //if (!string.IsNullOrEmpty(customerBetting.Rate))
            //{
            //    customerBettings.Add(customerBetting);

            //    client = new Client(_dataObject);
            //    if (drpBettingType.SelectedItem.Text.ToLower().Equals("match"))
            //    {
            //        client.UpdateClientMatchLimit(Convert.ToInt32(drpMatch.SelectedValue), Convert.ToInt32(cookie["ClientId"]));
            //    }
            //    else
            //    {

            //        client.UpdateClientLimit(Convert.ToInt32(cookie["ClientId"]), customerBetting.Rate);
            //    }
            //}



            #region Bind the Reports & Limit
            BindCustomersMatchReport();
            BindCustomersSessionReport();
            bindBettingLimit();
            #endregion
            if (customerBettings.Count > 0)
            {
                layerSuccess.Attributes.Add("style", "display:block;");
                layerSuccess.InnerHtml = "Betting Added Successfully!";
            }
            else
            {
                layerError.Attributes.Add("style", "display:block;");
                layerError.InnerHtml = "Please enter amount!";
            }

            txtSessionLagadiTeamA.Text = string.Empty;
            txtSessionLagadiTeamB.Text = string.Empty;
            txtSessionLagadiTeamTie.Text = string.Empty;
            txtSessionLagadiTeamDraw.Text = string.Empty;

            txtSessionKhadhiTeamA.Text = string.Empty;
            txtSessionKhadhiTeamB.Text = string.Empty;
            txtSessionKhadhiTeamTie.Text = string.Empty;
            txtSessionKhadhiTeamDraw.Text = string.Empty;
            btnSubmit.Visible = true;
            
            //}
        }
    }
    [WebMethod]
    public static List<GetSessionBettingForClientResult> GetBettingSessionRecords(int adminId, int matchId, int bettingType)
    {
        IDataRepository _dataObject1 = new DataRepository();
        CustomerBetting custBetting;

        custBetting = new CustomerBetting(_dataObject1);
        List<GetSessionBettingForClientResult> clientBettings = new List<GetSessionBettingForClientResult>();
        clientBettings = custBetting.GetSessionBettingForClient(adminId, matchId, bettingType);

        if (clientBettings != null && clientBettings.Count > 0)
            return clientBettings;
        else
            return null;
    }
    [WebMethod]
    public static List<GetScoreByMatchIdResult> GetScore(int matchId)
    {
        IDataRepository _dataObject1 = new DataRepository();
        Score score;

        score = new Score(_dataObject1);
        List<GetScoreByMatchIdResult> lstResult = new List<GetScoreByMatchIdResult>();
        lstResult = score.GetScoreByMatchId(matchId);

        if (lstResult != null && lstResult.Count > 0)
            return lstResult;
        else
            return null;
    }

    [WebMethod]
    public static List<GetCommonRateResult> getCurrentRate(int adminId)
    {
        IDataRepository _dataObject1 = new DataRepository();
        Admin admin;

        admin = new Admin(_dataObject1);
        List<GetCommonRateResult> lstResult = new List<GetCommonRateResult>();
        lstResult = admin.GetCommonRate(adminId);

        if (lstResult != null && lstResult.Count > 0)
            return lstResult;
        else
            return null;
    }
    private static DataTable GetData(string query)
    {
        string constr = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = query;
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataSet ds = new DataSet())
                    {
                        DataTable dt = new DataTable();
                        sda.Fill(dt);
                        return dt;
                    }
                }
            }
        }
    }
    private void BindCustomersMatchReport()
    {
        HttpCookie cookie = Request.Cookies["Client"];
        grdCustomerBettingMatch.Visible = true;

        matchSchedule = new MatchSchedule(_dataObject);
        List<GetMatchDetailsResult> lstResult = new List<GetMatchDetailsResult>();
        lstResult = matchSchedule.GetMatchDetails(Convert.ToInt32(drpMatch.SelectedValue));
        grdCustomerBettingMatch.Columns[1].HeaderText = lstResult[0].Abb1;
        grdCustomerBettingMatch.Columns[2].HeaderText = lstResult[0].Abb2;

        DataTable dt = new DataTable();
        
        //dt = GetData(string.Format("SELECT SUM(CAST(CB.Rate as decimal(18,2))) AS BettingAmount, SUM(CAST(TeamAAmount as decimal(18,2))) AS TeamAAmount, SUM(CAST(TeamBAmount as decimal(18,2))) AS TeamBAmount, SUM(CAST(TieAmount as decimal(18,2))) AS TieAmount, SUM(CAST(DrawAmount as decimal(8,2))) AS DrawAmount from Client C INNER JOIN CustomerBetting CB ON C.Id = CB.CreatedBy INNER JOIN Betting B ON B.Id = CB.BettingId INNER JOIN Team T ON T.Id = B.TeamId WHERE C.Id = '{0}' AND CB.MatchSchduleId = '{1}'  AND B.BettingTypeId = 2", Convert.ToInt32(cookie["ClientId"]), drpMatch.SelectedValue));
        dt = GetData(string.Format("SELECT SUM(CAST(CB.Rate as decimal(18,2))) AS BettingAmount, SUM(CAST(TeamAAmount as decimal(18,2))) AS TeamAAmount, SUM(CAST(TeamBAmount as decimal(18,2))) AS TeamBAmount, SUM(CAST(TieAmount as decimal(18,2))) AS TieAmount, SUM(CAST(DrawAmount as decimal(8,2))) AS DrawAmount from Client C INNER JOIN CustomerBetting CB ON C.Id = CB.CreatedBy INNER JOIN Betting B ON B.Id = CB.BettingId  WHERE C.Id = '{0}' AND CB.MatchSchduleId = '{1}'  AND B.BettingTypeId = 2", Convert.ToInt32(cookie["ClientId"]), drpMatch.SelectedValue));
        grdCustomerBettingMatch.DataSource = dt;
        grdCustomerBettingMatch.DataBind();

        //lblSTeamAAmount.Text = dt.Rows[0]["SUMTeamAAmount"].ToString();
        //lblSTeamBAmount.Text = dt.Rows[0]["SUMTeamBAmount"].ToString();
        //lblSDrawAmount.Text = dt.Rows[0]["SUMDrawAmount"].ToString();
    }
    private void BindCustomersSessionReport()
    {
        HttpCookie cookie = Request.Cookies["Client"];
        grdCustomerBettingSession.Visible = true;

        grdCustomerBettingSession.DataSource = GetData(string.Format("SELECT T.Abbrivation,b.[Over],CASE CB.BetFor WHEN 'L' THEN B.LagadiRate ELSE B.KhadhiRate END AS Rate, CASE CB.BetFor WHEN 'L' THEN 'L' ELSE 'K' END AS BettingFor,CB.Rate AS BettingAmount ,CONVERT(varchar(20),DATEADD(MI,30,DATEADD(hh,5,CB.CreatedDate)),113) As Date from Client C INNER JOIN CustomerBetting CB ON C.Id = CB.CreatedBy INNER JOIN Betting B ON B.Id = CB.BettingId INNER JOIN Team T ON T.Id = B.TeamId WHERE C.Id = '{0}' AND CB.MatchSchduleId = '{1}'  AND B.BettingTypeId = 1 ORDER BY CB.Createddate DESC", Convert.ToInt32(cookie["ClientId"]), drpMatch.SelectedValue));
        //grdCustomerBettingSession.DataSource = GetData(string.Format("SELECT SUM(CAST(CB.Rate as decimal(18,2))) As BettingTotal from Client C INNER JOIN CustomerBetting CB ON C.Id = CB.CreatedBy INNER JOIN Betting B ON B.Id = CB.BettingId INNER JOIN Team T ON T.Id = B.TeamId WHERE C.Id = '{0}' AND CB.MatchSchduleId = '{1}'  AND B.BettingTypeId = 1", Convert.ToInt32(cookie["ClientId"]), drpMatch.SelectedValue));
        grdCustomerBettingSession.DataBind();
    }
    protected void tossBetting_Click(object sender, EventArgs e)
    {
        Response.Redirect("Toss.aspx");
    }

    protected void grdCustomerBettingMatch_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (drpMatchType.SelectedItem.Text.ToLower() == "one day" || drpMatchType.SelectedItem.Text.ToLower() == "t20")
        {
            grdCustomerBettingMatch.Columns[3].Visible = false;
        }
        else
        {
            grdCustomerBettingMatch.Columns[3].Visible = true;
        }
    }
}